package api.cie.rss;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import api.cie.rss.adapters.ArticleListAdapter;
import api.cie.rss.common.Article;
import api.cie.rss.common.ParameterKeys;
import api.cie.rss.common.RSS;
import api.cie.rss.dal.ArticleDAL;
import api.cie.rss.dal.DatabaseAdapter;
import api.cie.rss.dal.ParameterDAL;
import api.cie.rss.dal.RssDAL;
import api.cie.rss.utils.ParserTools;
import api.cie.rss.utils.Utils;

public class MainActivity extends ListActivity {

	private static DatabaseAdapter dbAdapter;
	private List<Article> articles;

	public static DatabaseAdapter getDBAdapter() {
		return dbAdapter;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.article_list);
		initialize();		

		// Get the intent, verify the action and get the query
		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			doSearch(query);
		} else {
			display();
		}
	}	

	@Override
	protected void onResume() {
		super.onResume();
		fillData();
	}

	private void doSearch(String query) {
		dbAdapter.open();
		ArticleDAL articleDAL = new ArticleDAL(dbAdapter);		
		Cursor cursor = articleDAL.fetchArticlesByTitle(query);

		if (cursor != null) {
			for(int i=0; i<cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				articles.add(Utils.convertToArticle(cursor, dbAdapter));
			}
		}
		sortArticle();
		dbAdapter.close();		
		fillData();
	}

	private void initialize() {
		dbAdapter = new DatabaseAdapter(this);
		articles = new ArrayList<Article>();		

		ImageButton btnArchive = (ImageButton)findViewById(R.id.btnArchiveArticle);
		btnArchive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, FileChooserActivity.class);
				List<Article> selectedArticles = ((ArticleListAdapter)getListAdapter()).getSelectedArticles();
				if (selectedArticles != null && selectedArticles.size() > 0) {
					String xmlStr = ParserTools.toXML(selectedArticles);
					Bundle bundle = new Bundle();
					bundle.putString("xml", xmlStr);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			}
		});

		ImageButton btnFavorite = (ImageButton)findViewById(R.id.btnFavoriteArticles);
		btnFavorite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, FavoriteListActivity.class);
				startActivity(intent);
			}
		});

		ImageButton btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				articles.clear();
				dbAdapter.open();
				displayAll();
				sortArticle();
				dbAdapter.close();
				fillData();				
			}			
		});
	}

	private void displayAll() {
		ArticleDAL articleDAL = new ArticleDAL(dbAdapter);
		Cursor cursor = articleDAL.fetchAllArticles();			
		if (cursor != null) {
			for(int i=0; i<cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				Article tmp = Utils.convertToArticle(cursor, dbAdapter);
				if(tmp == null) continue;
				if(tmp.getRss() != null) {
					if(!tmp.getRss().isActive()) continue;
				}
				articles.add(tmp);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.settingsMenuItem:
			Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
			startActivity(intent);
			return true;
		case R.id.managefluxMenuItem:
			Intent intentRSS = new Intent(this, FluxListActivity.class);
			startActivity(intentRSS);
			return true;
		case R.id.searchMenuItem:
			return onSearchRequested();
		case R.id.refreshMenuItem:
			refreshData();			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}


	private void display() {
		articles.clear();
		dbAdapter.open();

		/*
		 * get the RSS of the articles to display
		 */		
		int idRSS = -1;
		Bundle bundle = getIntent().getExtras();
		if (bundle == null) {
			displayAll();
		} else {
			ArticleDAL articleDAL = new ArticleDAL(dbAdapter);
			idRSS = bundle.getInt(RssDAL.KEY_ROWID);
			if (idRSS > 0) {
				Cursor cursor = articleDAL.fetchArticlesByRSS(idRSS);
				if (cursor != null) {
					for(int i=0; i<cursor.getCount(); i++) {
						cursor.moveToPosition(i);
						articles.add(Utils.convertToArticle(cursor, dbAdapter));
					}
				}
			} else {
				String fileName = null;
				fileName = bundle.getString("fileName");
				if(fileName != null && !fileName.equals("")) {					
					try {
						FileInputStream stream = openFileInput(fileName);
						List<Article> tmp = ParserTools.getArticlesFromStream(stream);
						if(tmp != null) articles.addAll(tmp); 
						stream.close();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}					
				} 		
			}
		}
		sortArticle();
		dbAdapter.close();
		fillData();		

	}
	private void refreshData() {
		dbAdapter.open();
		articles.clear();
		ArticleDAL articleDAL = new ArticleDAL(dbAdapter);
		RssDAL rssDAL = new RssDAL(dbAdapter);

		// Delete all the articles in the database and get the new ones
		articleDAL.deleteAllArticle();
		Cursor cursorRSS = rssDAL.fetchAllRSS();
		for(int i=0; i<cursorRSS.getCount(); i++) {
			cursorRSS.moveToPosition(i);
			RSS rss = Utils.convertToRSS(cursorRSS, dbAdapter);
			if (rss != null) {
				if (!rss.isActive()) continue;
			}
			List<Article> articleRSS = ParserTools.getArticles(rss.getUrl());

			// Insert the new articles into the database
			for(Article a:articleRSS) {				
				a.setRss(rss);
				articleDAL.createArticle(a.getTitle(), a.getDescription(), a.getUrl(),
						cursorRSS.getInt(cursorRSS.getColumnIndex(RssDAL.KEY_ROWID)), 
						a.getRating(), Utils.dateToString(a.getPublishingDate()));
			}
			articles.addAll(articleRSS);
		}
		sortArticle();
		dbAdapter.close();
		fillData();
	}

	private void sortArticle() {
		if (articles.size() > 0) {
			ParameterDAL parameterDAL = new ParameterDAL(dbAdapter);
			Cursor cursor = parameterDAL.fetchParameterByKey(ParameterKeys.SORT_BY);
			if (cursor != null) {
				String sortType = cursor.getString(cursor.getColumnIndex(ParameterDAL.KEY_PARAMVALUE));
				if (sortType.equals(ParameterKeys.SORTBY_DATE)) {
					Utils.sortByDate(articles);
				} else if (sortType.equals(ParameterKeys.SORTBY_TITLE)){
					Utils.sortByTitle(articles);
				}
			} else {
				Utils.sortByDate(articles);
			}
		}
	}

	private void fillData() {
		ArticleListAdapter adapter = new ArticleListAdapter(this);		
		if(articles != null) {			
			adapter.addItems(articles);			
		} 

		setListAdapter(adapter);
	}
}